<?php

namespace app\cms\index;

use app\cms\service\dataoke\DataokePlatform;
use app\cms\service\entities\Good;
use app\cms\service\jd\JosPlatform;
use app\cms\service\SalesPlatformFactory;
use think\Controller;
use think\Response;

class Api extends Controller
{
    private JosPlatform $_josPlatform;

    private DataokePlatform $_dtkPlatform;

    protected $view = null;

    private function getJosPlatform(): JosPlatform
    {
        return $this->_josPlatform ?? ($this->_josPlatform = SalesPlatformFactory::getJosPlatform());
    }

    private function getDataokePlatform(): DataokePlatform
    {
        return $this->_dtkPlatform ?? ($this->_dtkPlatform = SalesPlatformFactory::getDataokePlatform());
    }

    protected function _initialize(){
        $this->view = null;
    }

    private function ok($data, $message = '', $code = 0) {
        return Response::create(compact('code', 'message', 'data'), 'Json');
    }

    private function err($message, $code = 1) {
        return Response::create(compact('message', 'code'), 'Json');
    }


    public function searchGoods($keyword, $page=1, $pageSize=20) {
        // TODO 检查 $queryWord 在系统指定的范围内
        // TODO 防刷，避免被京东淘宝拉黑。

//        $goodsList = [];
//        for ($i = 0; $i < 20; $i++) {
//            $good = new Good();
//            $good->clickUrl = 'https://www.baidu.com';
//            $good->picUrl = 'https://img20.360buyimg.com/babel/s320x320_jfs/t1/215691/12/18537/404898/62962d86E200e0082/97b0ac8b23ee0555.jpg!cc_320x320.webp';
//            $good->title = '模拟商品'.$i;
//            $good->rawPrice = 100 + $i;
//            $good->promPrice = 40 + $i - 0.4;
//            $good->platform = '京东';
//            $goodsList[] = $good;
//        }

        try {
            $goodsList = $this->getDataokePlatform()->queryGoods($keyword, $page, $pageSize);
            return $this->ok($goodsList);
        } catch (\Throwable $e) {
            return $this->err($e->getMessage());
        }

    }

    public function click($c) {
        try {
            $url = $this->getDataokePlatform()->convertClickUrl($c);
        } catch (\Throwable $e) {
            return $this->err($e->getMessage());
        }
        $this->redirect($url);
    }
}